class Solution
{
public:
    vector<int> topKFrequent(vector<int>& nums, int k)
    {
        unordered_map<int, int> freqMap;
        for (int num : nums)
            freqMap[num]++;

        int maxFreq = 0;
        for (const auto& [_, freq] : freqMap)
            maxFreq = max(maxFreq, freq);

        vector<vector<int>> buckets(maxFreq + 1);
        for (const auto& [element, freq] : freqMap)
            buckets[freq].push_back(element);

        vector<int> ans;
        for (int i = maxFreq; i >= 0 && ans.size() < k; --i)
            if (!buckets[i].empty())
                for (int x : buckets[i])
                {
                    ans.push_back(x);
                    if (ans.size() == k)
                        return ans;
                }

        return ans;
    }
};